
//交易对MQTT经理类
const WeexMqtt = weex.requireModule("WeexMqtt");

import math from "@/_js/math";

var topicRuns = {}; //运行主题
var sendMsgs = {}; //合约发送消息
var topicPairs = {}; //交易对主题
var timeSendMsg = undefined; //发送消息定时器

export default {
  
  //初始化运行Mqtt主题
  initMqttRunTopic(datas){

    topicRuns = {};
    sendMsgs = {};
    topicPairs = {};
    for (let index = 0; index < datas.length; index++) {
      var data = datas[index];
      if (data.isContract != 'contract_usdt') {
        continue;
      }

      //运行主题（订阅、发送)
      var topicRun = this.geTopicRun(data.isContract, data.executeId);
      topicRuns[topicRun] = topicRun;

      //合约发送的消息
      var pair = JSON.parse(data.config).tradePairs[0];
      sendMsgs[topicRun] = this.getContractSendMsg(data.apiId, pair.contractId);

      //交易对主题
      var topicPair = this.geTopicPair(pair.exchangeName, pair.counterCoin, 'USDT');
      topicPairs[topicPair] = topicPair;
    }
  },

  //mqtt订阅主题
  mqttSubscribes() {
    if (JSON.stringify(topicRuns) == '{}'){
      return;
    }

    //1、清除旧订阅
    WeexMqtt.unSubscribes(); 

    //2、"运行" 主题
    var topics = [];
    for (var key in topicRuns) {
      var topic = 'consume' + '/' + key;
      topics.push(topic);
    }

    //3、‘交易对’ 主题
    for (var key in topicPairs) {
      topics.push(key);
    }

    //4、订阅
    WeexMqtt.subscribes(topics);
  },

  //取消订阅
  unSubscribes() {
    if(timeSendMsg){
      clearTimeout(timeSendMsg);
    }
    WeexMqtt.message(null);
    WeexMqtt.unSubscribes();
  },

  //mqtt发送消息
  mqttSendMsg() {
    if (JSON.stringify(topicRuns) == '{}'){
      return;
    }

    //1、清除延时循环发送
    if(timeSendMsg){
      clearTimeout(timeSendMsg);
    }
  
    //2、发送消息
    for (var key in topicRuns) {
      var topic = 'make' + '/' + key;
      var msg = sendMsgs[key];
      WeexMqtt.publishData(msg, topic);
    }

    //3、延时循环发送
    timeSendMsg = setTimeout(() => {
      this.mqttSendMsg();
    }, 5000);
  },

  /** 获取运行主题（订阅、发送）
   * 
   * @param {String} type 策略类型-合约、现货
   * @param {String} executeId 执行ID
   */
  geTopicRun(type, executeId) {
    var topic = 'strategy' + '/' + type + '/' +  executeId;
    return topic;
  },

  /** 获取交易对主题
   * 
   * @param {String} exchangeName 交易所
   * @param {String} counterCoin 交易币
   * @param {String} baseCoin 本币
   */
  geTopicPair(exchangeName, counterCoin , baseCoin) {
    exchangeName = exchangeName.toUpperCase();
    counterCoin = counterCoin.toUpperCase();
    baseCoin = baseCoin.toUpperCase();
    var topic = 'public/market/contract/' + exchangeName + '/' + baseCoin + '/' +counterCoin;
    return topic;
  },

  /** 获取合约发送的消息
   * 
   * @param {String} apiId apiId
   * @param {String} contractId 合约编号
   */
  getContractSendMsg(apiId, contractId) {
    var array = [apiId, contractId]
    var msg = JSON.stringify(array);
    return msg;
  },

  /** 获取交易对订阅消息
   * 
   * @param {JSON} data 订阅消息 
   */
  getPairMsg(data) {
    var topic = data.topic;
    if (topicPairs[topic]) {
      var messages = JSON.parse(data.message);
      var last = messages[0];
      return (last == '') ? undefined : last;
    }
    return undefined;
  },

  /** 获取运行订阅消息
   * 
   * @param {JSON} data 订阅消息 
   */
  getRunMsg(data) {

    var topic = data.topic.replace('consume/', '');
    if (topicRuns[topic]) {
      var array = topic.split('/');
      var executeId = array[2];
      var message = JSON.parse(data.message);
      
       //账户权益
      var marginBalance = message[0];
      marginBalance = (marginBalance == '') ? undefined : math.gfCoin(marginBalance, 'USDT');;

      //资产担保率
      var riskRate = message[1]; 
      riskRate = (riskRate == '') ? undefined : math.cheng(riskRate,"100", 2, 2);;

      //持仓盈亏
      var floatEarnings = message[3]; 
      floatEarnings = (floatEarnings == '') ? undefined : math.xiaoShuDelete0(floatEarnings);

      //持仓盈亏率
      var floatEarningsRate = message[4]; 
      floatEarningsRate = (floatEarningsRate == '') ? undefined : math.xiaoShuDelete0(floatEarningsRate);

      return {'executeId':executeId,
              'marginBalance':marginBalance,
              'riskRate':riskRate, 
              'floatEarnings':floatEarnings, 
              'floatEarningsRate':floatEarningsRate};
    }
    return undefined;
  },
}